//
//  JoSignViewController.m
//  RunningMan
//  
//  Created by 姜勇利 on 16/5/20.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//

#import "JoSignViewController.h"
#import "masonry.h"
#import "EMSDk.h"
#import "JoUserNavigationViewController.h"
#import "JoPrivatismViewController.h"
#import "CoreDataManager.h"
#import "Privatism.h"
#import <BmobSDK/Bmob.h>

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface JoSignViewController ()<UITextFieldDelegate>

@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *passWord;
@property (nonatomic, copy) NSString *entryWord;

@end

@implementation JoSignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatSubViews];
}
#pragma mark -
- (void)creatSubViews
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:backImage];
    backImage.image = [UIImage imageNamed:@"Q4GVX.jpeg"];
    backImage.userInteractionEnabled = YES;
    
// 返回按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backImage addSubview:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(30);
        make.left.equalTo(self.view).with.offset(10);
        make.width.height.mas_equalTo(25);
    }];
    [cancelButton setImage:[UIImage imageNamed:@"4"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(handleCancel:) forControlEvents:UIControlEventTouchUpInside];
 
// 注册用户名输入框
    UITextField *userNameText = [[UITextField alloc]init];
    [backImage addSubview:userNameText];
    userNameText.delegate = self;
    NSAttributedString *string = [[NSAttributedString alloc]initWithString:@"请输入用户名" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    userNameText.attributedPlaceholder = string;
    userNameText.textAlignment = YES;
    userNameText.tag = 100;
    [userNameText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(WIDTH * 2 / 3.f);
        make.top.equalTo(self.view).with.offset(HEIGHT / 4.f);
        make.height.mas_equalTo(HEIGHT / 22.f);
    }];
    UIImageView *userView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"20"]];
    userView.frame = CGRectMake(0, 0, HEIGHT /22.f, HEIGHT / 22.f);
    userNameText.leftViewMode = UITextFieldViewModeAlways;
    userNameText.leftView = userView;
    
    UIView *line1View = [[UIView alloc]init];
    [backImage addSubview:line1View];
    line1View.backgroundColor = [UIColor whiteColor];
    [line1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(1.5);
        make.width.mas_equalTo(WIDTH * 2 / 3.f);
        make.top.equalTo(userNameText.mas_bottom).with.offset(2);
    }];
    
    UITextField *passWordText = [[UITextField alloc]init];
    [backImage addSubview:passWordText];
    passWordText.secureTextEntry = YES;
    NSAttributedString *stringPass = [[NSAttributedString alloc]initWithString:@"请输入密码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    passWordText.attributedPlaceholder = stringPass;
    passWordText.textAlignment = YES;
    passWordText.tag = 200;
    passWordText.delegate = self;
    [passWordText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(WIDTH * 2 / 3.f);
        make.top.equalTo(line1View.mas_bottom).with.offset(HEIGHT / 20.f);
        make.height.mas_equalTo(HEIGHT / 22.f);
    }];
    UIImageView *passView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"21"]];
    passView.frame = CGRectMake(0, 0, HEIGHT /22.f, HEIGHT / 22.f);
    passWordText.leftViewMode = UITextFieldViewModeAlways;
    passWordText.leftView = passView;
    UIView *line2View = [[UIView alloc]init];
    [backImage addSubview:line2View];
    line2View.backgroundColor = [UIColor whiteColor];
    [line2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(1.5);
        make.width.mas_equalTo(WIDTH * 2 / 3.f);
        make.top.equalTo(passWordText.mas_bottom).with.offset(2);
    }];
    
    UITextField *entryWordText = [[UITextField alloc]init];
    [backImage addSubview:entryWordText];
    entryWordText.tag = 300;
    entryWordText.delegate = self;
    NSAttributedString *stringEntry = [[NSAttributedString alloc]initWithString:@"请再次输入密码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    entryWordText.attributedPlaceholder = stringEntry;
    entryWordText.textAlignment = YES;
    entryWordText.secureTextEntry = YES;
    [entryWordText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(WIDTH * 2 / 3.f);
        make.top.equalTo(line2View.mas_bottom).with.offset(HEIGHT / 20.f);
        make.height.mas_equalTo(HEIGHT / 22.f);
    }];
    UIImageView *entryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"23"]];
    entryView.frame = CGRectMake(0, 0, HEIGHT /22.f, HEIGHT / 22.f);
    entryWordText.leftViewMode = UITextFieldViewModeAlways;
    entryWordText.leftView = entryView;
    UIView *line3View = [[UIView alloc]init];
    [backImage addSubview:line3View];
    line3View.backgroundColor = [UIColor whiteColor];
    [line3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(1.5);
        make.width.mas_equalTo(WIDTH * 2 / 3.f);
        make.top.equalTo(entryWordText.mas_bottom).with.offset(2);
    }];

    UIButton *signButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backImage addSubview:signButton];
    [signButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(WIDTH / 2.f);
        make.top.equalTo(line3View.mas_bottom).with.offset(HEIGHT / 12.f);
        make.height.mas_equalTo(HEIGHT / 20.f);
    }];
    signButton.layer.borderColor = [[UIColor whiteColor]CGColor];
    signButton.clipsToBounds = YES;
    signButton.layer.borderWidth = 1.5;
    signButton.layer.cornerRadius = 8;
    [signButton setTitle:@"注册" forState:UIControlStateNormal];
    signButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [signButton addTarget:self action:@selector(handleSign:) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handlecancel:)];
    [self.view addGestureRecognizer:tap];
}
#pragma mark - textField协议方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag == 100) {
        NSLog(@"%@", textField.text);
        self.userName = [NSString stringWithFormat:@"%@", textField.text];
    }
    if (textField.tag == 200) {
        self.passWord = [NSString stringWithFormat:@"%@", textField.text];
    }
    if (textField.tag == 300) {
        self.entryWord = [NSString stringWithFormat:@"%@", textField.text];
    }
}

#pragma mark - 响应事件
- (void)handleSign:(UIButton *)button
{
    [self.view endEditing:YES];
    if (self.userName != nil && self.passWord != nil && self.entryWord != nil && [self.entryWord isEqualToString:self.passWord]) {
        EMError *error = [[EMClient sharedClient] registerWithUsername:self.userName password:self.passWord];
        if (error==nil) {
            NSLog(@"注册成功");
            JoPrivatismViewController *primaryPage = [[JoPrivatismViewController alloc]init];
            JoUserNavigationViewController *userPageN = [[JoUserNavigationViewController alloc]initWithRootViewController:primaryPage];
            NSInteger runID = arc4random() % (99999999 - 10000000 + 1) + 10000000;
            NSMutableArray *mArrPhotos = [NSMutableArray array];
            NSMutableDictionary *mDicPicturesDate = [NSMutableDictionary dictionary];

    // Bmob
            BmobObject *userInfo = [BmobObject objectWithClassName:@"userInfo"];
            [userInfo setObject:self.userName forKey:@"userName"];
            [userInfo setObject:@"请填写昵称" forKey:@"name"];
            [userInfo setObject:mArrPhotos forKey:@"image"];
            [userInfo setObject:[NSNumber numberWithInteger:3] forKey:@"sex"];
            [userInfo setObject:@"无" forKey:@"autogrph"];
            [userInfo setObject:[NSNumber numberWithInteger:runID] forKey:@"runID"];
            [userInfo setObject:mDicPicturesDate forKey:@"date_Pic"];
    // 异步保存到服务器
            [userInfo saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    // 创建成功后会返回objectId，updateAt，createdAt等信息
                    // 创建成功后，打印对象值
                    NSLog(@"用户信息:%@", userInfo);
                    [[NSUserDefaults standardUserDefaults]setObject:userInfo.objectId forKey:@"objectId"];
                }
                else if (error)
                {
                    NSLog(@"%@", error);
                }
                else
                {
                    NSLog(@"Unknow error");
                }
            }];
            
            BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
            if (!isAutoLogin) {
                EMError *error = [[EMClient sharedClient] loginWithUsername:self.userName password:self.passWord];
                if (!error)
                {
                    [[EMClient sharedClient].options setIsAutoLogin:YES];
                }
            }
            [self presentViewController:userPageN animated:YES completion:^{
                
            }];
        }
        else
        {
            NSLog(@"~~~~~~~~~%@", error.description);
        }
    }
    else{
        NSLog(@"输入帐号或密码有误");
        NSLog(@"%@ %@ %@", self.userName, self.passWord, self.entryWord);
    }
}

- (void)handlecancel:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
}

// 返回按钮
- (void)handleCancel:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark -
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.view endEditing:YES];
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
